/*
 * @Author: your name
 * @Date: 2021-07-13 11:22:22
 * @LastEditTime: 2021-07-31 09:32:07
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hrsaas\src\permission.js
 */
import router from './router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 白名单
const whileList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 判断有没有token
  if (store.getters.token) {
    // 如果有token 直接去主页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
    if (!store.getters.userId) {
      const { roles } = await store.dispatch('user/getUserInfo')
      // const result = await store.dispatch('user/getUserInfo')
      // console.log(result)

      console.log(roles)
      // 筛选得到当前用户可用的动态路由
      const routes = await store.dispatch('permission/filterRoutes', roles.menus)
      console.log(routes)
      // 添加动态路由到路由表
      console.log(router.options.routes)

      router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
      console.log(router.options.routes)
      // 多做一个跳转
      next(to.path)
    } else {
      next()
    }
  } else {
    // 如果没有token
    // next('/');

    if (whileList.indexOf(to.path) > -1) {
      // 表示要去的地址在白名单
      next()
    } else {
      // 跳到登录页
      next('/login')
    }
  }
  NProgress.done()
})
// 后置守卫
router.afterEach(function() {
  // 关闭进度条
  NProgress.done()
})
